/** file AudioAlsa.cpp
    author belot.nicolas
*/

#include "AudioAlsa.h"
#include "nbalsa.h"
#include <iostream>
#include <cassert>
#ifdef HAVE_LIBALSA
namespace libtrckr {

double *AudioAlsa::_buffer=0;
int AudioAlsa::cnt=0;

int alsa_process(int nframes, void* arg){
	//std::cout << "copy " << std::endl;
	AudioAlsa *a=(AudioAlsa*)arg;
	if( a->getFrames(nframes,AudioAlsa::_buffer) > 0){
		memcpy(a->getAlsaBuffer(), AudioAlsa::_buffer, sizeof(double)*nframes*a->channels());
		return nframes;
	}
	return 0;
}

AudioAlsa::AudioAlsa(){
	_buffer=0;
	cnt++;
}

AudioAlsa::AudioAlsa(const AudioAlsa& a){
	channels(a.channels());
	bitrate(a.bitrate());
	_buffer=0;
	cnt++;
}


AudioAlsa::~AudioAlsa(){
	if(_buffer!=0){
		free(_buffer);
	}
	/*cnt--;
	if(cnt<=0 && sbuffer!=0){
		free(sbuffer);
	}*/
}
void AudioAlsa::open(){
	if(!*lock){
	if(_buffer==0){
		_buffer=(double*)malloc(sizeof(double)*2048);
	}
	if(sbuffer==0){
		sbuffer=(double*)malloc(sizeof(double)*bitrate()*channels());//thats bad i know...
		*capacity=bitrate()*channels();
	}
	//Meme si sbuffer est déjà créer nous ne somme pas sur de son contenu.
	*start=0;
	*end=0;
	*size=0;
		
	alsa_set_callback(alsa_process,this );
	uint rate=bitrate();
	short bsize=64;
	stream = alsa_get_stream(&rate,&bsize);
	if(stream==NULL){
		_state=INVALID;
	}else{
		std::cout << "Stream open, rate : " << rate << ", size " << bsize << std::endl;
		_state=OPEN;
	}
	std::cout << "size : " << *capacity << std::endl;
	*lock=true;
	}
}

Audio::audio_state_t AudioAlsa::state(){
	return _state;
}

double *AudioAlsa::getAlsaBuffer(){
	return alsa_getIn();
}

void AudioAlsa::close(){
	alsa_close_stream(stream);
	_state=CLOSE;
	*lock=false;
}


int AudioAlsa::append(Buffer b){
	if(*size+(b.size()*b.channels())>*capacity){
		return 0;
	}else{
		copy(b);
	}

}

void AudioAlsa::param(std::string name, std::string value){}

void AudioAlsa::param(std::string name, double value){}
void AudioAlsa::param(std::string name, int value){}

}

#endif
